<?php
namespace adminv1\auth; 
use adminv1\CoreController;
use Yii;
use admin\models\auth\AuthRule;
use admin\models\auth\Roles;
use admin\models\auth\AuthApi;
/*
	用户权限相关控制器
*/

class AuthRuleController extends CoreController
{
    protected function getModelClass(): string
    {
        return AuthRule::class;
    }

	/*
		获取菜单列表
		pid 父id
	*/
	public function actionAuthRuleList()
	{
		$pid = $this->request('pid');
		$data = AuthRule::getChildMenu();
		$extend = ['apiFlag' => \Yii::$app->params['apiAuth']];
		return $this->success('权限列表'.$pid, $data, $extend);
	}


	//编辑菜单
	public function actionEditAuthRule()
	{
		$authRule = new AuthRule;
		$params = $this->request;
		if(isset($params['id']) && $params['id'] > 0){
			$authRule = $authRule::findOne($params['id']);
		}else{
			$params['create_time'] = $this->curDateTime;
		}
		
		try{
			$transaction = \Yii::$app->db->beginTransaction();
			if(!$authRule->load($params, '') || !$authRule->validate() || !$authRule->save() )
			{	
				throw new \Exception("操作失败");
			}
			if(!$params['id']) $authRule->id = Yii::$app->db->getLastInsertID();

			## 添加对应的api路由
			if(!$this->updateApiAuth($authRule->id)) throw new \Exception("api auth err");

			$transaction->commit();
			return $this->success('操作成功',$authRule->attributes);

		}catch(\Exception $e)
		{
			$transaction->rollback();
			return $this->error($e->getMessage());
		}
	}

	##更新接口权限
	private function updateApiAuth($ruleId)
	{
		$apiPaths = $this->request('api_paths');
		$apiArr = $apiPaths ? json_decode($apiPaths,1):[];

		if(!\Yii::$app->params['apiAuth'] && !$apiArr) return true;
		if(\Yii::$app->params['apiAuth'] && !$apiArr) return true;

		$ids = [];
		foreach($apiArr as &$api)
		{
			$api['rule_id'] = $ruleId;
			if(isset($api['id']) && $api['id'] > 0){
				$apiModel = AuthApi::findOne(['id'=>$api['id']]);
			}else{
				$apiModel = new AuthApi;
				$api['create_time'] = $this->curDateTime;
			}
			if(!$apiModel->load($api,'') || !$apiModel->validate() || !$apiModel->save()){
				$errMsg = $apiModel::outError($apiModel->getErrors());
				throw new \Exception($errMsg['msg']);
				return false;
			}
			if(empty($api['id'])) $apiModel->id = \Yii::$app->db->getLastInsertID();
			$ids[] = $apiModel->id;
		}

		## 删除不存在的api
		AuthApi::deleteAll(['and',['not in','id',$ids],['rule_id'=>$ruleId]]);
		return true;
	}


	//删除菜单
	//id
	public function actionDelAuthRule()
	{
		if(!$id = $this->request('id')) return $this->error('参数错误');

		$delMenu = AuthRule::getChildMenu($id);
		$ids = [$id];
		if($delMenu)
		{
			foreach($delMenu as $menu)
			{
				$ids[] = $menu;
			}			
		}
		$where = ['in','id',$ids];
		$res = AuthRule::deleteAll($where);

		if($res) return $this->success('删除成功');
		return $this->error('删除失败');

	}


}